"""
专家分析智能体
负责对抓取的数据进行深度分析和总结
"""

import json
from datetime import datetime
from typing import Dict, List, Any

from autogen_agentchat.agents import AssistantAgent
from autogen_ext.models.openai import OpenAIChatCompletionClient


class ExpertAgent(AssistantAgent):
    """数据分析专家智能体"""

    def __init__(self, name: str, model_client: OpenAIChatCompletionClient, config: Any):
        system_message = """
        你是一个资深的数据分析专家，专门负责分析软件开发项目数据。

        你的职责：
        1. 接收数据抓取员提供的 TAPD 工作项数据
        2. 进行深度数据分析，包括：
           - 工作量分析（预估vs实际工时）
           - 完成率和效率分析
           - 优先级分布分析
           - 工作类型分布分析
           - 团队成员工作负载分析
        3. 识别关键趋势和问题：
           - 工时预估准确度
           - 项目延期情况
           - 质量问题（缺陷率）
           - 团队协作效率
        4. 提供数据洞察和改进建议
        5. 为报告生成提供分析结论

        分析要求：
        - 使用统计学方法进行量化分析
        - 提供具体的数字和百分比
        - 识别异常数据和潜在问题
        - 给出可操作的改进建议
        """

        super().__init__(
            name=name,
            model_client=model_client,
            system_message=system_message
        )
        self.config = config

    def analyze_work_data(self, raw_data: Dict[str, Any]) -> Dict[str, Any]:
        """
        分析工作数据

        Args:
            raw_data: 原始工作数据

        Returns:
            分析结果字典
        """

        analysis_results = {
            "analysis_time": datetime.now().isoformat(),
            "summary": {},
            "detailed_analysis": {},
            "insights": [],
            "recommendations": []
        }

        # 收集所有工作项
        all_items = []
        all_items.extend(raw_data.get("stories", []))
        all_items.extend(raw_data.get("tasks", []))
        all_items.extend(raw_data.get("bugs", []))

        # 基础统计
        total_items = len(all_items)
        total_estimated_hours = sum(item.get("estimated_hours", 0) for item in all_items)
        total_actual_hours = sum(item.get("actual_hours", 0) for item in all_items)

        # 完成状态分析
        completed_items = [item for item in all_items if item.get("status") in ["已完成", "已修复"]]
        completion_rate = (len(completed_items) / total_items * 100) if total_items > 0 else 0

        # 工时预估准确度
        estimation_accuracy = []
        for item in all_items:
            estimated = item.get("estimated_hours", 0)
            actual = item.get("actual_hours", 0)
            if estimated > 0:
                accuracy = (1 - abs(estimated - actual) / estimated) * 100
                estimation_accuracy.append(accuracy)

        avg_estimation_accuracy = sum(estimation_accuracy) / len(estimation_accuracy) if estimation_accuracy else 0

        # 优先级分布
        priority_distribution = {}
        for item in all_items:
            priority = item.get("priority", "未知")
            priority_distribution[priority] = priority_distribution.get(priority, 0) + 1

        # 工作类型分布
        type_distribution = {
            "需求": len(raw_data.get("stories", [])),
            "任务": len(raw_data.get("tasks", [])),
            "缺陷": len(raw_data.get("bugs", []))
        }

        # 团队成员工作负载
        assignee_workload = {}
        for item in all_items:
            assignee = item.get("assignee", "未分配")
            if assignee not in assignee_workload:
                assignee_workload[assignee] = {
                    "total_items": 0,
                    "total_hours": 0,
                    "completed_items": 0
                }

            assignee_workload[assignee]["total_items"] += 1
            assignee_workload[assignee]["total_hours"] += item.get("actual_hours", 0)

            if item.get("status") in ["已完成", "已修复"]:
                assignee_workload[assignee]["completed_items"] += 1

        # 汇总分析结果
        analysis_results["summary"] = {
            "total_work_items": total_items,
            "completion_rate": round(completion_rate, 2),
            "total_estimated_hours": total_estimated_hours,
            "total_actual_hours": total_actual_hours,
            "estimation_accuracy": round(avg_estimation_accuracy, 2),
            "efficiency_ratio": round(total_estimated_hours / total_actual_hours * 100, 2) if total_actual_hours > 0 else 0
        }

        analysis_results["detailed_analysis"] = {
            "priority_distribution": priority_distribution,
            "type_distribution": type_distribution,
            "assignee_workload": assignee_workload
        }

        # 生成洞察
        insights = []
        if completion_rate >= 90:
            insights.append("✅ 项目完成率较高，团队执行力强")
        elif completion_rate >= 70:
            insights.append("⚠️ 项目完成率中等，需要关注未完成项目")
        else:
            insights.append("❌ 项目完成率偏低，需要分析阻塞原因")

        if avg_estimation_accuracy >= 80:
            insights.append("✅ 工时预估准确度较高，说明团队对工作量把握较好")
        elif avg_estimation_accuracy >= 60:
            insights.append("⚠️ 工时预估准确度中等，建议提升预估能力")
        else:
            insights.append("❌ 工时预估准确度偏低，需要改进预估方法")

        efficiency_ratio = analysis_results["summary"]["efficiency_ratio"]
        if efficiency_ratio >= 100:
            insights.append("✅ 实际执行效率高于预期")
        elif efficiency_ratio >= 80:
            insights.append("⚠️ 实际执行效率基本符合预期")
        else:
            insights.append("❌ 实际执行效率低于预期，需要分析原因")

        analysis_results["insights"] = insights

        # 生成改进建议
        recommendations = []

        if completion_rate < 90:
            recommendations.append("建议加强项目跟踪，及时识别和解决阻塞问题")

        if avg_estimation_accuracy < 80:
            recommendations.append("建议引入历史数据分析，提升工时预估准确性")
            recommendations.append("可以考虑采用敏捷估点法或三点估算法")

        if len(raw_data.get("bugs", [])) / total_items > 0.2:
            recommendations.append("缺陷占比较高，建议加强代码审查和测试质量")

        # 检查工作负载均衡
        if assignee_workload:
            workloads = [data["total_hours"] for data in assignee_workload.values()]
            if max(workloads) - min(workloads) > 20:
                recommendations.append("团队工作负载不均衡，建议优化任务分配")

        analysis_results["recommendations"] = recommendations

        return analysis_results

    def format_analysis_results(self, analysis_results: Dict[str, Any]) -> str:
        """
        格式化分析结果为可读格式

        Args:
            analysis_results: 分析结果字典

        Returns:
            格式化的分析报告字符串
        """

        formatted_output = []
        formatted_output.append("# 数据分析报告")
        formatted_output.append("")

        # 核心指标摘要
        summary = analysis_results.get("summary", {})
        formatted_output.append("## 📊 核心指标摘要")
        formatted_output.append(f"- **工作项总数**: {summary.get('total_work_items', 0)}")
        formatted_output.append(f"- **完成率**: {summary.get('completion_rate', 0)}%")
        formatted_output.append(f"- **预估工时**: {summary.get('total_estimated_hours', 0)}h")
        formatted_output.append(f"- **实际工时**: {summary.get('total_actual_hours', 0)}h")
        formatted_output.append(f"- **预估准确度**: {summary.get('estimation_accuracy', 0)}%")
        formatted_output.append(f"- **执行效率**: {summary.get('efficiency_ratio', 0)}%")
        formatted_output.append("")

        # 详细分析
        detailed = analysis_results.get("detailed_analysis", {})

        # 优先级分布
        priority_dist = detailed.get("priority_distribution", {})
        if priority_dist:
            formatted_output.append("## 🎯 优先级分布")
            for priority, count in priority_dist.items():
                percentage = count / summary.get('total_work_items', 1) * 100
                formatted_output.append(f"- **{priority}**: {count} 项 ({percentage:.1f}%)")
            formatted_output.append("")

        # 工作类型分布
        type_dist = detailed.get("type_distribution", {})
        if type_dist:
            formatted_output.append("## 📋 工作类型分布")
            for work_type, count in type_dist.items():
                percentage = count / summary.get('total_work_items', 1) * 100
                formatted_output.append(f"- **{work_type}**: {count} 项 ({percentage:.1f}%)")
            formatted_output.append("")

        # 团队工作负载
        assignee_workload = detailed.get("assignee_workload", {})
        if assignee_workload:
            formatted_output.append("## 👥 团队工作负载")
            for assignee, workload in assignee_workload.items():
                completion_rate = workload["completed_items"] / workload["total_items"] * 100 if workload["total_items"] > 0 else 0
                formatted_output.append(f"- **{assignee}**: {workload['total_items']} 项, {workload['total_hours']}h, 完成率 {completion_rate:.1f}%")
            formatted_output.append("")

        # 关键洞察
        insights = analysis_results.get("insights", [])
        if insights:
            formatted_output.append("## 💡 关键洞察")
            for insight in insights:
                formatted_output.append(f"- {insight}")
            formatted_output.append("")

        # 改进建议
        recommendations = analysis_results.get("recommendations", [])
        if recommendations:
            formatted_output.append("## 🚀 改进建议")
            for i, recommendation in enumerate(recommendations, 1):
                formatted_output.append(f"{i}. {recommendation}")
            formatted_output.append("")

        return "\n".join(formatted_output)